package com.hyts.rpclet.handler;

import com.google.common.base.Preconditions;
import com.hyts.rpclet.annotation.RpcletBean;
import com.hyts.rpclet.constant.RpcletConst;
import com.hyts.rpclet.constant.RpcletSerializeType;
import com.hyts.rpclet.context.RpcletContext;
import com.hyts.rpclet.core.RpcletServerDispatcher;
import com.hyts.rpclet.execute.RpcletMethodInvoker;
import com.hyts.rpclet.serialize.RpcletSerializer;
import com.hyts.rpclet.util.SpringContextUtils;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.rpclet.handle
 * author:Libo/Alex
 * create-date:2019-07-09 21:40
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: rpcletContext服务处理器
 */
@Component
public class RpcletServerHandler extends AbstractHandler {


    @Autowired
    RpcletContext rpcletContext;

    @Autowired
    SpringContextUtils springContextUtils;

    @Autowired
    RpcletServerDispatcher rpcletServerDispatcher;


    @Override
    public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
        //操作s服务
        if(s.startsWith(RpcletConst.DEFAULT_RPCLET_PROTOCOL_NAME)){
            String targetPath = s.toLowerCase();
            RpcletMethodInvoker rpcletMethodInvoker = rpcletContext.get(targetPath);
            Preconditions.checkArgument(rpcletMethodInvoker == null,"获取相关对于rpc对象,请检查相关对应服务");
            rpcletServerDispatcher.invoke(rpcletMethodInvoker,request.getInputStream(),
                    httpServletResponse.getOutputStream());
            httpServletResponse.setContentType(RpcletSerializeType.JSON.getContentType());
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            httpServletResponse.getOutputStream().flush();
            request.setHandled(true);
        }
        return ;
    }
}
